package cn.edu.scnu.semart.message.service.impl;

import cn.edu.scnu.semart.model.chat.ChatMessage;
import cn.edu.scnu.semart.message.mapper.ChatMessageMapper;
import cn.edu.scnu.semart.message.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ChatMessageServiceImpl implements ChatMessageService {
    private static final String REDIS_KEY_PREFIX = "chat:msg:";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Override
    public void saveMessageToRedis(ChatMessage message) {
        String key = REDIS_KEY_PREFIX + message.getConversationId();
        redisTemplate.opsForList().rightPush(key, message);
        redisTemplate.expire(key, 2, TimeUnit.DAYS);
    }

    @Override
    public List<ChatMessage> getMessagesFromRedis(String conversationKey) {
        List<Object> list = redisTemplate.opsForList().range(conversationKey, 0, -1);
        return list != null ? (List<ChatMessage>)(List<?>)list : null;
    }

    @Override
    public void removeMessagesFromRedis(String conversationKey) {
        redisTemplate.delete(conversationKey);
    }

    @Override
    public void saveMessagesToMySQL(List<ChatMessage> messages) {
        for (ChatMessage msg : messages) {
            chatMessageMapper.insert(msg);
        }
    }
} 